package gqlgencs

import (
	"context"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/auths"
	"gitee.com/shiqiyue/gqlgenc/clientv2"
	"github.com/opentracing/opentracing-go"
	"github.com/opentracing/opentracing-go/ext"
	"net/http"
)

func AuthorizationInterceptor() clientv2.RequestInterceptor {
	return func(ctx context.Context, req *http.Request, gqlInfo *clientv2.GQLRequestInfo, res interface{}, next clientv2.RequestInterceptorFunc) error {
		token, ok := req.Context().Value(auths.TOKEN_KEY).(*string)
		if ok && token != nil {
			req.Header.Add(auths.TOKEN_HEADER, *token)
		}
		return next(ctx, req, gqlInfo, res)
	}
}

func OpenTracingInterceptor() clientv2.RequestInterceptor {
	return func(ctx context.Context, req *http.Request, gqlInfo *clientv2.GQLRequestInfo, res interface{}, next clientv2.RequestInterceptorFunc) error {
		var parentCtx opentracing.SpanContext
		if parent := opentracing.SpanFromContext(ctx); parent != nil {
			parentCtx = parent.Context()
		}
		sp := opentracing.StartSpan(
			gqlInfo.Request.OperationName,
			opentracing.FollowsFrom(parentCtx),
			ext.SpanKindRPCClient,
		)
		_ = opentracing.GlobalTracer().Inject(sp.Context(), opentracing.HTTPHeaders, req.Header)
		defer sp.Finish()
		return next(ctx, req, gqlInfo, res)
	}
}
